package com.xjve.framework.hibernate.query.core;

import com.xjve.framework.hibernate.query.exception.SqlQueryException;
import com.xjve.framework.hibernate.query.model.SqlTemplate;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.StringTemplateResolver;

import java.util.Map;

/**
 * Thymeleaf模板引擎实现
 */
public class ThymeleafTemplateEngine implements TemplateEngine {

    private final org.thymeleaf.TemplateEngine sqlTemplateEngine;
    private final Map<String, SqlTemplate> sqlTemplates;

    public ThymeleafTemplateEngine(Map<String, SqlTemplate> sqlTemplates) {
        this.sqlTemplates = sqlTemplates;
        this.sqlTemplateEngine = createThymeleafEngine();
    }

    /**
     * 创建Thymeleaf引擎
     */
    private org.thymeleaf.TemplateEngine createThymeleafEngine() {
        org.thymeleaf.TemplateEngine engine = new org.thymeleaf.TemplateEngine();

        // 创建字符串模板解析器
        StringTemplateResolver resolver = new StringTemplateResolver();
        resolver.setTemplateMode(TemplateMode.TEXT);
        resolver.setCacheable(false); // 开发环境不缓存

        engine.setTemplateResolver(resolver);

        // 添加自定义方言支持#include语法
        engine.addDialect(new SqlIncludeDialect(sqlTemplates));

        return engine;
    }

    @Override
    public String compile(String templateName, Map<String, Object> parameters) {
        SqlTemplate template = sqlTemplates.get(templateName);
        if (template == null) {
            throw new SqlQueryException("SQL template not found: " + templateName);
        }

        return compileContent(template.getContent(), parameters);
    }

    @Override
    public String compileContent(String templateContent, Map<String, Object> parameters) {
        try {
            Context context = new Context();
            if (parameters != null) {
                context.setVariables(parameters);
            }

            // 使用Thymeleaf编译模板
            return sqlTemplateEngine.process(templateContent, context);

        } catch (Exception e) {
            throw new SqlQueryException("Failed to compile SQL template", e);
        }
    }
}
